/**
 * 
 */
package com.android.dwt.ui;

import java.util.ArrayList;
import java.util.Collections;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences.Editor;
import android.os.Bundle;
import android.util.Log;
import android.view.ContextMenu;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.view.Window;
import android.widget.AdapterView;
import android.widget.AdapterView.AdapterContextMenuInfo;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.CheckedTextView;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.android.dwt.R;
import com.android.dwt.R.id;
import com.android.dwt.R.layout;
import com.android.dwt.data.GTDApp;
import com.android.dwt.util.Utils;

/**
 * @author xiang
 * 
 */
public class TagAct extends Activity implements
		OnClickListener, DialogInterface.OnClickListener {
	
	private static final String TAG = "TacAct";
	private static final int MENU_RENAME = 0;
	private static final int MENU_DELETE = 1;
	public static final int RESULT_TAG = 2;
	public static final int TAG_CANCELED = 3;
	
	private ArrayAdapter<String> mAdapter;
	private GTDApp ga;
	private ArrayList<Integer> alSelect = new ArrayList<Integer>();
//	Bundle bd;
	private ListView mListView;
	private int selectPos;
	private String selectStr;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);

		requestWindowFeature(Window.FEATURE_CUSTOM_TITLE);
		setContentView(R.layout.view_tag);
		getWindow().setFeatureInt(Window.FEATURE_CUSTOM_TITLE, R.layout.tb_cmn);
		
		((TextView) findViewById(R.id.tv_title)).setText("选择标签");

		ga = (GTDApp) getApplication();

		mListView = (ListView) findViewById(R.id.lv_tag);
		mAdapter = new ArrayAdapter<String>(
				this,
				R.layout.my_mul_list_item,
				ga.getTags());
		mListView.setAdapter(mAdapter);
		mListView.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
		
		Intent intent = getIntent();
		int size = intent.getIntExtra("tag_count", -1);
		
		alSelect.clear();
		alSelect = intent.getIntegerArrayListExtra("selected");
		for (int i=0; i<size; i++) {
			
			mListView.setItemChecked(alSelect.get(i).intValue(), true);
		}

		handleEvent();
		
		registerForContextMenu(mListView);
	}
	
	@Override
	protected void onStart() {
		
		super.onStart();
		
		Log.e(TAG, "onStart method is called!");
	}
	
	private void handleEvent() {
		
		ImageButton btn_new = (ImageButton) findViewById(R.id.btn_new);
		btn_new.setOnClickListener(this);
		
		mListView.setOnItemClickListener(new OnItemClickListener() {
			
			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
					long arg3) {
				
				Log.e(TAG, "position " + arg2 + " is clicked! ");
				
				// String str = (String) mListView.getItemAtPosition(arg2);
				CheckedTextView ctv = (CheckedTextView) arg1;
				if (ctv.isChecked()) {
					
					alSelect.remove(Integer.valueOf(arg2));
					
				} else {
					
					alSelect.add(Integer.valueOf(arg2));
				}
				
			}
			
		});
		
		((Button) findViewById(R.id.btn_tag_ok)).setOnClickListener(this);
		((Button) findViewById(R.id.btn_tag_cal)).setOnClickListener(this);
		
		ImageButton ibReturn = (ImageButton) findViewById(R.id.btn_return);
		ibReturn.setOnClickListener(this);
		ibReturn.setOnTouchListener(new OnTouchListener() {
			
			@Override
			public boolean onTouch(View v, MotionEvent event) {
				
				if (event.getAction() == MotionEvent.ACTION_DOWN) {
					
					v.setBackgroundResource(R.drawable.back_pressed);
					
				} else if (event.getAction() == MotionEvent.ACTION_UP) {
					
					v.setBackgroundResource(R.drawable.back);
				}

				return false;
			}
			
		});
	}

	@Override
	public void onCreateContextMenu(ContextMenu menu, View v,
			ContextMenu.ContextMenuInfo menuInfo) {
		
		super.onCreateContextMenu(menu, v, menuInfo);
		
		AdapterContextMenuInfo info = (AdapterContextMenuInfo) menuInfo;
		
		selectPos = info.position;
		selectStr = mListView.getItemAtPosition(info.position).toString();
		
		Log.e(TAG, "selectPos= "+selectPos+" selectStr= "+selectStr);
		
//		CheckedTextView view = (CheckedTextView) info.targetView;
//		if (!view.isChecked()) {		// edit this item if it is not checked
			
    		menu.setHeaderTitle("编辑标签");
    		
    		menu.add(0, MENU_RENAME, Menu.NONE, "重命名");
    		menu.add(0, MENU_DELETE, Menu.NONE, "删除");
//		}
		
	}

	@Override
	public boolean onContextItemSelected(MenuItem item) {
		
//		super.onContextItemSelected(item);

		switch (item.getItemId()) {
		
    		case (MENU_RENAME): // edit item
    			
    			renameTag();
    			
    			return true;
    			
    		case (MENU_DELETE): // delete item
    			
    			deleteTag();
    			
    			return true;
    			
    		default:
    			break;
		}

		return false;
	}

	private void addTag() {
		
		LayoutInflater li = LayoutInflater.from(this);
	    View view = li.inflate(R.layout.dlg_input, null);
	    
	    AlertDialog.Builder builder = new AlertDialog.Builder(this);
	    builder.setTitle("添加新标签");
	    
	    builder.setView(view);
	    builder.setPositiveButton("确定", this);
	    builder.setNegativeButton("取消", this);
	    builder.create().show();
	}
	
	private void renameTag() {
		
		LayoutInflater li = LayoutInflater.from(this);
	    View view = li.inflate(R.layout.dlg_input, null);
	    
	    final EditText input = (EditText) view.findViewById(R.id.et_input);
	    input.setText(selectStr);
	    input.selectAll();
	    
	    AlertDialog.Builder builder = new AlertDialog.Builder(this);
	    
	    builder.setTitle("添加新标签");
	    builder.setView(view);
	    
	    builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
			
			@Override
			public void onClick(DialogInterface dialog, int which) {
				
				AlertDialog ad = (AlertDialog) dialog;
				String str = input.getText().toString();
				
				if (str.length() > 0) {
					
					ArrayList<String> al = ga.getTags();
					
					if (al.contains(str)) {		// duplicate tag
						
						Utils.closeAlertDialog(ad, false);
						
						Toast.makeText(TagAct.this,
								"标签不能重复", Toast.LENGTH_LONG)
							.show();
						
						input.selectAll();
						
						return;
					}

					al.set(selectPos, str);
					ga.setTags(al);
					
					Editor edit = ga.getSpTags().edit();
					edit.putInt("count", al.size());
					edit.putString("Tag[" + selectPos + "]", selectStr);
					edit.commit();
					
					mAdapter.notifyDataSetChanged();
					
					dialog.dismiss();
					
				} else {
					
					Utils.closeAlertDialog(ad, false);
					
					Toast.makeText(TagAct.this,
							"标签不能为空", Toast.LENGTH_LONG)
						.show();
				}
				
			}
			
		});
	    
	    builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
			
			@Override
			public void onClick(DialogInterface dialog, int which) {
				
				Utils.closeAlertDialog((AlertDialog) dialog, true);
				
				dialog.dismiss();
			}
			
		});
	    
	    builder.create().show();
	}
	
	private void deleteTag() {
		
		ArrayList<String> al = ga.getTags();
		al.remove(selectPos);
		ga.setTags(al);
		
		// update check state in list view
		int index = -1;
		for (int i=0; i<alSelect.size(); i++) {
			
			if (alSelect.get(i).intValue() == selectPos) {
				
				index = i;
				break;
			}
			
		}
		
		if (index != -1) {
			
			// update index
			for (int i=index+1; i<alSelect.size(); i++) {
				
				Integer integer = alSelect.get(i);
				alSelect.set(i, integer-1);
			}
			
			alSelect.remove(index);
		}
		
		for (int i=0; i<mListView.getCount(); i++) {
			
			mListView.setItemChecked(i, false);
		}
		
		for (int i=0; i<alSelect.size(); i++) {
			
			mListView.setItemChecked(alSelect.get(i).intValue(), true);
		}
		
		mAdapter.notifyDataSetChanged();
		
		// update shared preferences
		Editor edit = ga.getSpTags().edit();
		edit.putInt("count", al.size());
		
//		edit.remove("Tag[" + selectPos + "]");
		for (int i=selectPos+1; i<=al.size(); i++) {
			
			String tag = ga.getSpTags().getString("Tag[" + i + "]", "");
			edit.putString("Tag[" + (i-1) + "]", tag);
		}
		edit.remove("Tag[" + al.size() + "]");
		
		edit.commit();
	}
	
	@Override
	public void onClick(View v) {
		
		Intent i = null;
		
		switch (v.getId()) {
		
    		case R.id.btn_new:
    			
    			addTag();
    		    
    			break;
    			
    		case R.id.btn_tag_ok:
    			
    			Collections.sort(alSelect);
    			
    			i = new Intent();
				
				i.putExtra("tag_count", alSelect.size());
				i.putIntegerArrayListExtra("selected", alSelect);
				
				setResult(RESULT_TAG, i);
				
				finish();
    			
    			break;
    			
    		case R.id.btn_tag_cal:
    		case R.id.btn_return:
    			
    			Collections.sort(alSelect);
    			
    			i = new Intent();
				
				i.putExtra("tag_count", alSelect.size());
				i.putIntegerArrayListExtra("selected", alSelect);
				
				setResult(TAG_CANCELED, i);
				
    			finish();
    			
    			break;
    			
    		default:
    			break;
		}
		
		return;
	}
	
	@Override
	public void onClick(DialogInterface dialog, int which) {
		
		AlertDialog ad = (AlertDialog) dialog;
		
		switch (which) {
		
    		case Dialog.BUTTON_POSITIVE:
    			
    			EditText et = (EditText) ad.findViewById(R.id.et_input);
				String str = et.getText().toString();
				
				if (str.length() > 0) {
					
					ArrayList<String> al = ga.getTags();
					
					if (al.contains(str)) {		// duplicate tag
						
						Utils.closeAlertDialog(ad, false);
						
						Toast.makeText(TagAct.this,
								"标签不能重复", Toast.LENGTH_LONG)
							.show();
						
						et.selectAll();
						
						return;
					}
					
					al.add(str);
					ga.setTags(al);
					
					Editor edit = ga.getSpTags().edit();
					edit.putInt("count", al.size());
					edit.putString("Tag[" + (al.size()-1) + "]", str);
					edit.commit();
					
					mAdapter.notifyDataSetChanged();
					
					Utils.closeAlertDialog(ad, true);
					ad.dismiss();
					
				} else {			// empty input
					
					Utils.closeAlertDialog(ad, false);
					
					Toast.makeText(TagAct.this,
							"标签不能为空", Toast.LENGTH_LONG)
						.show();

					return;
				}
				
    			break;
    			
    		case Dialog.BUTTON_NEGATIVE:
    			
    			Utils.closeAlertDialog(ad, true);
    			
    			ad.dismiss();
    			
    			break;
    			
    		default:
    			break;
		}
		
		return;
	}

}
